use log::{info, warn};
use std::process::Command;
use std::path::Path;

/// 文档格式
#[derive(Debug, Clone, Copy)]
pub enum DocFormat {
    Markdown,
    Html,
    Both,
}

/// 文档生成器
pub struct DocGenerator {
    project_root: String,
}

impl DocGenerator {
    pub fn new() -> Self {
        Self {
            project_root: std::env::current_dir()
                .unwrap_or_default()
                .to_string_lossy()
                .to_string(),
        }
    }

    /// 检查并安装依赖
    pub fn check_and_install_dependencies(&self) -> Result<(), String> {
        info!("🔍 检查文档生成依赖...");

        // 检查Python
        if !self.check_python() {
            info!("❌ Python未安装");
            info!("");
            info!("📦 安装Python:");
            if cfg!(target_os = "windows") {
                info!("   Windows:");
                info!("   1. 访问: https://www.python.org/downloads/");
                info!("   2. 下载并安装Python 3.12+");
                info!("   3. 安装时勾选 'Add Python to PATH'");
                info!("");
                info!("   或使用winget安装:");
                info!("   winget install Python.Python.3.12");
            } else {
                info!("   Linux:");
                info!("   sudo apt update");
                info!("   sudo apt install python3 python3-pip");
                info!("");
                info!("   或 (CentOS/RHEL):");
                info!("   sudo yum install python3");
            }
            return Err("请先安装Python后再运行文档生成功能".to_string());
        }

        // 检查pandoc
        if !self.check_pandoc() {
            warn!("⚠️  Pandoc未安装，将只能生成Markdown格式");
            info!("");
            info!("📦 安装Pandoc (可选，用于生成HTML):");
            if cfg!(target_os = "windows") {
                info!("   Windows:");
                info!("   winget install --id JohnMacFarlane.Pandoc");
                info!("");
                info!("   或访问: https://pandoc.org/installing.html");
            } else {
                info!("   Linux:");
                info!("   sudo apt install pandoc");
                info!("");
                info!("   或 (CentOS/RHEL):");
                info!("   sudo yum install pandoc");
            }
            info!("");
        } else {
            info!("✅ Pandoc已安装");
        }

        Ok(())
    }

    /// 检查Python是否安装
    fn check_python(&self) -> bool {
        let result = if cfg!(target_os = "windows") {
            Command::new("python").arg("--version").output()
        } else {
            Command::new("python3").arg("--version").output()
        };

        match result {
            Ok(output) => {
                if output.status.success() {
                    let version = String::from_utf8_lossy(&output.stdout);
                    info!("✅ Python已安装: {}", version.trim());
                    true
                } else {
                    false
                }
            }
            Err(_) => false,
        }
    }

    /// 检查Pandoc是否安装
    fn check_pandoc(&self) -> bool {
        let username = std::env::var("USERNAME").unwrap_or_default();
        let user_pandoc = format!(r"C:\Users\{}\AppData\Local\Pandoc\pandoc.exe", username);
        
        // 尝试多个可能的路径
        let pandoc_paths: Vec<String> = if cfg!(target_os = "windows") {
            vec![
                "pandoc".to_string(),
                r"C:\Program Files\Pandoc\pandoc.exe".to_string(),
                r"C:\Program Files (x86)\Pandoc\pandoc.exe".to_string(),
                user_pandoc,
            ]
        } else {
            vec![
                "pandoc".to_string(),
                "/usr/bin/pandoc".to_string(),
                "/usr/local/bin/pandoc".to_string(),
            ]
        };

        for pandoc_path in &pandoc_paths {
            if let Ok(output) = Command::new(pandoc_path).arg("--version").output() {
                if output.status.success() {
                    return true;
                }
            }
        }

        false
    }

    /// 生成文档
    pub fn generate_docs(&self, format: DocFormat) -> Result<Vec<String>, String> {
        info!("📚 开始生成项目文档...");
        info!("========================================");

        let mut generated_files = Vec::new();

        // 检查生成脚本是否存在
        let script_path = Path::new(&self.project_root).join("generate_pdf_tutorial.py");
        if !script_path.exists() {
            return Err("文档生成脚本不存在: generate_pdf_tutorial.py".to_string());
        }

        // 运行Python脚本生成Markdown
        info!("🔄 生成Markdown文档...");
        let python_cmd = if cfg!(target_os = "windows") { "python" } else { "python3" };
        
        let output = Command::new(python_cmd)
            .arg(script_path.to_str().unwrap())
            .current_dir(&self.project_root)
            .output()
            .map_err(|e| format!("执行Python脚本失败: {}", e))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(format!("生成文档失败: {}", stderr));
        }

        // Markdown总是会生成
        let md_path = Path::new(&self.project_root).join("tutorial.md");
        if md_path.exists() {
            info!("✅ Markdown文档已生成: tutorial.md");
            generated_files.push("tutorial.md".to_string());
        }

        // 如果需要HTML格式
        if matches!(format, DocFormat::Html | DocFormat::Both) {
            if self.check_pandoc() {
                info!("🔄 生成HTML文档...");
                self.generate_html()?;
                
                let html_path = Path::new(&self.project_root)
                    .join("task_execute_scheduler_tutorial.html");
                if html_path.exists() {
                    info!("✅ HTML文档已生成: task_execute_scheduler_tutorial.html");
                    generated_files.push("task_execute_scheduler_tutorial.html".to_string());
                }
            } else {
                warn!("⚠️  无法生成HTML: Pandoc未安装");
            }
        }

        info!("========================================");
        info!("✅ 文档生成完成");
        info!("");

        Ok(generated_files)
    }

    /// 生成HTML文档
    fn generate_html(&self) -> Result<(), String> {
        let md_path = Path::new(&self.project_root).join("tutorial.md");
        let html_path = Path::new(&self.project_root)
            .join("task_execute_scheduler_tutorial.html");

        // 查找pandoc
        let pandoc_cmd = self.find_pandoc()
            .ok_or("找不到pandoc命令")?;

        let output = Command::new(&pandoc_cmd)
            .arg(md_path.to_str().unwrap())
            .arg("-o")
            .arg(html_path.to_str().unwrap())
            .arg("--standalone")
            .arg("--toc")
            .arg("--toc-depth=3")
            .arg("--highlight-style=monokai")  // 使用monokai代码高亮
            .arg("--metadata")
            .arg("title=Task Execute Scheduler 教程")
            .current_dir(&self.project_root)
            .output()
            .map_err(|e| format!("执行pandoc失败: {}", e))?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Err(format!("生成HTML失败: {}", stderr));
        }

        // 注入黑色主题CSS
        self.inject_dark_theme(&html_path)?;

        Ok(())
    }

    /// 注入黑色主题CSS到HTML
    fn inject_dark_theme(&self, html_path: &Path) -> Result<(), String> {
        use std::fs;
        
        let html_content = fs::read_to_string(html_path)
            .map_err(|e| format!("读取HTML文件失败: {}", e))?;

        // 读取CSS文件
        let css_content = include_str!("dark_theme.css");
        
        // 在</head>之前插入CSS
        let css_tag = format!("<style>\n{}\n</style>\n</head>", css_content);
        let new_html = html_content.replace("</head>", &css_tag);
        
        fs::write(html_path, new_html)
            .map_err(|e| format!("写入HTML文件失败: {}", e))?;
        
        Ok(())
    }

    /// 查找pandoc可执行文件
    fn find_pandoc(&self) -> Option<String> {
        let username = std::env::var("USERNAME").unwrap_or_default();
        let user_pandoc_path = format!(r"C:\Users\{}\AppData\Local\Pandoc\pandoc.exe", username);
        
        let pandoc_paths = if cfg!(target_os = "windows") {
            vec![
                "pandoc".to_string(),
                r"C:\Program Files\Pandoc\pandoc.exe".to_string(),
                r"C:\Program Files (x86)\Pandoc\pandoc.exe".to_string(),
                user_pandoc_path,
            ]
        } else {
            vec![
                "pandoc".to_string(),
                "/usr/bin/pandoc".to_string(),
                "/usr/local/bin/pandoc".to_string(),
            ]
        };

        for path in pandoc_paths {
            if let Ok(output) = Command::new(&path).arg("--version").output() {
                if output.status.success() {
                    return Some(path);
                }
            }
        }

        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_check_python() {
        let generator = DocGenerator::new();
        // 这个测试依赖环境，所以只是确保不会panic
        let _ = generator.check_python();
    }
}
